// 订阅者模式（事件中心），可以将一些事件统一发布到事件中心，由事件中心统一发布到订阅者。
const eventNames: string[] = [] // 事件类型，自己定义，如'APP:UN_AUTH'(登录失效/未登录)
class EventEmitter {
  private events: { [key: string]: Function[] } = {} as { [key: string]: Function[] }

  constructor() {
    eventNames.forEach(eventName => {
      this.events[eventName] = []
    })
  }

  on(eventName: string, callback: Function) {
    if (!this.events[eventName]) {
      this.events[eventName] = []
    }
    this.events[eventName].push(callback)
  }

  emit(eventName: string, ...args: any[]) {
    if (this.events[eventName]) {
      this.events[eventName].forEach(callback => {
        callback(...args)
      })
    }
  }

  off(eventName: string, callback: Function) {
    if (this.events[eventName]) {
      // 清空回调函数
      if (callback) {
        this.events[eventName] = this.events[eventName].filter(item => item !== callback)
      } else {
        this.events[eventName] = []
      }
    }
  }
}

export default new EventEmitter()
